package com.shelpe.services.sinbad.controller.sinbad;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.shelpe.services.sinbad.controller.dto.EffectDto;
import com.shelpe.services.sinbad.controller.dto.redis.RedisDto;
import com.shelpe.services.sinbad.entity.jpa.User;
import com.shelpe.services.sinbad.entity.mongo.BusinessCostRtr;
import com.shelpe.services.sinbad.repository.jpa.UserRepository;
import com.shelpe.services.sinbad.repository.mongo.BusinessCostRtrRepository;
import com.shelpe.services.sinbad.service.mq.ShelpeMQProducerService;
import com.shelpe.services.sinbad.utils.DateUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping(value = "/sinbadservice/v2")
@Api("账户实时数据业务相关的API")
@Slf4j
public class RealtimeReport2Controller {

	@Autowired
	private BusinessCostRtrRepository businessCostRtrRepository;
	@Autowired
	private ShelpeMQProducerService mqProducerService;
	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private UserRepository userRepository;

	@ApiOperation("唤醒实时花费数据接口")
	@RequestMapping(path = "/users/{user_id}/@sync_realtime_cost", method = RequestMethod.GET)
	public Reponse notifySyncRealtimeCost(@PathVariable("user_id") long userID,
			@RequestParam(name = "type", required = false, defaultValue = "manual") String type) {
		User user = this.userRepository.findOne(userID);
		Assert.notNull(user, "该用户不存在");
		if (user.getEstablished() != 1 && user.getUserType() == 1) {
			Reponse res = new Reponse();
			res.setStatus(false);
			return res;
		}
		Date date = new Date();
		RedisDto dto = new RedisDto();
		dto.setUserID(userID);
		dto.setType(type);
		dto.setNotifyTime(date.getTime());
		log.debug("start notifySyncRealtimeCost user:{} dto:{}", dto.getUserID(), dto);
		if ("manual".equals(type)) {
			this.mqProducerService.sendMsgForLoginSync(this.serialize(dto));
		} else {
			this.mqProducerService.sendMsgForOptimize(this.serialize(dto));
		}

		Reponse res = new Reponse();
		res.setStatus(true);
		return res;
	}

	@Data
	private static class Reponse {
		private boolean status;
	}

	@ApiOperation("获取账户实时报表数据趋势数据")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "user_id", value = "淘宝用户id", required = true, paramType = "path", dataType = "long") })
	@RequestMapping(path = "/users/{user_id}/reports/@get_realtime_cost", method = RequestMethod.GET)
	public RealtimeEffectDto getRealtimeCost(@PathVariable("user_id") long userID) {
		List<BusinessCostRtr> todayMonPos = this.businessCostRtrRepository.findByUserIDAndLogDate(userID,
				DateUtil.parseDate2date(DateFormatUtils.format(new Date(), "yyyy-MM-dd")));
		List<BusinessCostRtr> yesterdayMonPos = this.businessCostRtrRepository.findByUserIDAndLogDate(userID,
				DateUtil.parseDate2date(DateFormatUtils.format(DateUtils.addDays(new Date(), -1), "yyyy-MM-dd")));

		RealtimeEffectDto dto = new RealtimeEffectDto();
		dto.setToday(new ArrayList<EffectDto>());
		dto.setYesterday(new ArrayList<EffectDto>());
		if (todayMonPos != null && todayMonPos.size() > 0) {
			for (BusinessCostRtr po : todayMonPos) {
				if (po.getMetric() != null) {
					EffectDto effect = po.getMetric();
					effect.setMinuteDate(po.getDate());
					dto.getToday().add(effect);
				}
			}
		}
		if (yesterdayMonPos != null && yesterdayMonPos.size() > 0) {
			for (BusinessCostRtr po : yesterdayMonPos) {
				if (po.getMetric() != null) {
					EffectDto effect = po.getMetric();
					effect.setMinuteDate(po.getDate());
					dto.getYesterday().add(effect);
				}
			}
		}
		return dto;
	}

	@Data
	public static class RealtimeEffectDto {
		private List<EffectDto> today;
		private List<EffectDto> yesterday;

	}

	public String serialize(RedisDto po) {
		try {
			return objectMapper.writeValueAsString(po);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
